﻿Imports System.Xml.Serialization
Imports Framework.Data

Partial Public Class Manager
    Private Sub New()
    End Sub

    Public Shared Sub Start()
        FileShare.Engine.Manager.Start()

        Framework.Settings.Provider.RegisterTab(Settings.SettingsKey, GetType(SettingsControl))
        Handler_Activities.Start()
    End Sub

    Public Shared Sub [Stop](ByVal message As Framework.Message)
        message.SetMessage("Shutting down fileshare plug in...")
        FViewSharedItems.CloseAll()
        FViewSharedItemDetails.CloseAll()
        Handler_Activities.Stop()
        FileShare.Engine.Manager.Stop(message)
    End Sub

    Friend Shared Function StartDownload(ByVal owner As IWin32Window, ByVal node As Framework.Net.Node, ByVal item As Engine.Commands.GetShareItems.ItemInfo) As Boolean
        If String.IsNullOrEmpty(Settings.IncomingFilesDirectory) Then
            Select Case MessageBox.Show(owner, "You need to set your download directory before starting downloads. Would you like to do that now?", "Start Download", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                Case DialogResult.Yes
                    If Not Framework.Settings.Provider.ShowDialog(owner, "FileShare") Then Return False
                Case Else
                    Return False
            End Select
        ElseIf Not IO.Directory.Exists(Settings.IncomingFilesDirectory) Then
            Select Case MessageBox.Show(owner, "Your download directory does not exist or you do not have access permissions for it. Would you like to change you download directory now?", "Start Download", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                Case DialogResult.Yes
                    If Not Framework.Settings.Provider.ShowDialog(owner, "FileShare") Then Return False
                Case Else
                    Return False
            End Select
        End If

        Dim strDownloadingDir As String = Settings.DownloadingFilesDirectory
        If Not IO.Directory.Exists(strDownloadingDir) Then
            IO.Directory.CreateDirectory(strDownloadingDir)
        End If

        'first, get a list of all files in the item
        Dim aFiles As Generic.List(Of Entities.SharedItemFile)
        aFiles = Manager.GetAllItemFiles(node, item.Id)

        For i As Integer = aFiles.Count - 1 To 0 Step -1
            Dim clsFile As Entities.SharedItemFile = aFiles(i)
            If DoWeAlreadyHaveThisFile(clsFile.SHA512Hash, clsFile.Size) Then
                aFiles.RemoveAt(i)
            ElseIf AreWeAlreadyDownloadingThisFile(clsFile.SHA512Hash, clsFile.Size) Then
                aFiles.RemoveAt(i)
            End If
        Next
        If aFiles.Count = 0 Then
            MessageBox.Show(owner, "You already either have all files in this item, or you're already downloading them!", "Start Download", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Return False
        End If

        'check and see if we already have this move, in another format/release
        If item.Type = Entities.ItemType.Movies Then
            If Not MakeSureWeDontHaveThisMovie(owner, item) Then
                Return False
            End If
        End If

        FileShare.Engine.Manager.StartDownload(item, aFiles)
        Return True
    End Function

    Private Shared Function DoWeAlreadyHaveThisFile(ByVal sha512Hash As String, ByVal size As Long) As Boolean
        Dim clsFile As Entities.SharedItemFile = EntityHandlers.SharedItemsFiles.GetBySHA512HashAndSizeNotOrphaned(sha512Hash, size)
        Return clsFile IsNot Nothing
    End Function
    Private Shared Function AreWeAlreadyDownloadingThisFile(ByVal sha512Hash As String, ByVal size As Long) As Boolean
        Dim clsFile As Entities.Downloads.File = EntityHandlers.DownloadsFiles.GetBySHA512HashAndSize(sha512Hash, size)
        If clsFile IsNot Nothing AndAlso clsFile.Status = Entities.Downloads.Status.Deleted Then
            Return False
        ElseIf clsFile IsNot Nothing Then
            Return True
        Else
            Return False
        End If
    End Function
    Private Shared Function MakeSureWeDontHaveThisMovie(ByVal owner As IWin32Window, ByVal item As Engine.Commands.GetShareItems.ItemInfo) As Boolean
        If item.ExternalIds Is Nothing Then Return True
        If item.ExternalIds.Count = 0 Then Return True
        Dim aExistingMovies As Generic.List(Of Entities.MediaInfo) = EntityHandlers.MediaInfo.GetAllByFeatureIds(item.ExternalIds)
        If aExistingMovies.Count = 0 Then Return True

        Dim aIds As Generic.List(Of Integer) = (From mi In aExistingMovies Select mi.SharedItemId).ToList
        Dim aItems As Generic.List(Of Entities.SharedItem)
        aItems = EntityHandlers.SharedItems.GetAllByIds(aIds)
        Dim clsView As New FShowExistingFeatures
        Select Case clsView.ShowDialog(owner, My.Resources.Movie.ToBitmap, "movie", aItems, aExistingMovies)
            Case DialogResult.Yes
                Return True
            Case Else
                Return False
        End Select
    End Function


    Public Shared Sub DeleteShare(ByVal share As Entities.Share)
        EntityHandlers.Shares.Delete(share.Id)
    End Sub

    Public Shared Function GetAllItemFiles(ByVal node As Framework.Net.Node, ByVal sharedItemId As Integer) As Generic.List(Of Entities.SharedItemFile)
        Return Engine.Commands.GetSharedItemFiles.Execute(node, sharedItemId)
    End Function

    Public Shared Sub ModifyOpenMediaInfo(ByVal item As Entities.SharedItem)
        Dim clsView As New FHandleMissingFeatureActivity
        clsView.Show(item)
    End Sub

End Class

Public Class PlugIn
    Implements Framework.Plugin.IPlugIn

    Private mUC As FileSharingTabControl

    Friend Const TabKey As String = "FileShare"

    Private Sub Start(ByVal host As Framework.Plugin.IHost) Implements Framework.Plugin.IPlugIn.Start
        Manager.Start()
        mUC = New FileSharingTabControl
        mUC.Init()
        host.AddTabImage(TabKey, Framework.My.Resources.Share.ToBitmap)
        host.AddTab(TabKey, TabKey, "File Sharing", mUC)
    End Sub
    Private Sub [Stop](ByVal message As Framework.Message) Implements Framework.Plugin.IPlugIn.Stop
        mUC.Stop()
        mUC = Nothing
        Manager.Stop(message)
    End Sub
    Private Sub MenuItemClicked(ByVal menuItemKey As String) Implements Framework.Plugin.IPlugIn.MenuItemClicked
    End Sub
End Class